package com.qf.jie.controller.filter;

import com.alibaba.fastjson.JSON;
import com.qf.jie.entity.vo.RespBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //1.处理 post 提交方式的乱码问题
        request.setCharacterEncoding("utf-8");

        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        String servletPath = req.getServletPath();
        String type = req.getParameter("type");

        // 先判断是否登录，已登录就直接放行
        Object user = req.getSession().getAttribute("user");
        if (user != null){
            filterChain.doFilter(req, resp);
            return;
        }

        // 不拦截的请求
        if ("/UserController".equals(servletPath) && ("login".equals(type) || "register".equals(type)) ){
            filterChain.doFilter(req, resp);
            return;
        }


        resp.getWriter().write(JSON.toJSONString(RespBean.respError("not login")));
        System.out.println(servletPath + "   " + type);
    }

    @Override
    public void destroy() {

    }
}
